﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using RRRSRoguelike.Enums;
using RRRSRoguelike.Helpers.Actions;

namespace RRRSRoguelike.Managers
{
	/// <summary>
	/// Stores a list of actions along with the keys mapped to those actions
	/// Checks action map against the inputmanager
	/// </summary>
	public class ActionManager
	{
		#region variables
		/// <summary>
		/// Holds a list of mapped actions
		/// </summary>
		public ActionMap[] ActionMap;
		
		/// <summary>
		/// Holds a list of the Direction vetors.
		/// </summary>
		public Dictionary<string, Point> DirectionVectors;
		
		/// <summary>
		/// delegate for actions
		/// </summary>
		public delegate void ActionHandler(object sender,EventArgs  args);
		InputManager InputManager = ApplicationManager.Instance.InputManager;
		#endregion

		#region methods
		/// <summary>
		/// initializes the action manager
		/// </summary>
		/// <param name="numberOfActions"></param>
		public void Initialize(int numberOfActions)
		{
			ActionMap = new ActionMap[numberOfActions];
			for (int i = 0; i < numberOfActions; i++)
				ActionMap[i] = new ActionMap();

			SetupDirectionVectors();
		}

		/// <summary>
		/// Maps action to key
		/// </summary>
		/// <param name="action"></param>
		/// <param name="key"></param>
		public void SetButtons(Actions action, ConsoleKey key)
		{
			ActionMap[(int)action].ConsoleKeys.Add(key);
			//ActionMap[(int)action].ActionEvent;
		}
		
		/// <summary>
		/// maps action to key and includes an event
		/// </summary>
		/// <param name="action"></param>
		/// <param name="key"></param>
		/// <param name="actionEvent"></param>
		public void SetButtons(Actions action, ConsoleKey key, ActionHandler actionEvent)
		{
			ActionMap[(int)action].ConsoleKeys.Add(key);
			ActionMap[(int)action].ActionEvent = actionEvent;
		}

		/// <summary>
		/// return true if action is pushed
		/// </summary>
		/// <param name="Action"></param>
		/// <returns></returns>
		public bool IsActionPushed(Actions Action)
		{
			for (int i = 0; i < ActionMap[(int)Action].ConsoleKeys.Count(); i++)
			{
				if (InputManager.KeyPush(ActionMap[(int)Action].ConsoleKeys[i]))
				{
					return true;
				}
			}
			return false;
		}

		private void SetupDirectionVectors()
		{
			DirectionVectors = new Dictionary<string, Point>
			{
				{Direction.N.ToString(), new Point(0, -1)},
				{Direction.NE.ToString(), new Point(1, -1)},
				{Direction.E.ToString(), new Point(1, 0)},
				{Direction.SE.ToString(), new Point(1, 1)},
				{Direction.S.ToString(), new Point(0, 1)},
				{Direction.SW.ToString(), new Point(-1, 1)},
				{Direction.W.ToString(), new Point(-1, 0)},
				{Direction.NW.ToString(), new Point(-1, -1)}
			};
		}


		#endregion

	}

}
